#include "ChessProcessor.h"
#include "ChessDatabase.h"
#include "FeatureExtractor.h"
#include <iostream>
#include <vector>
#include <string>
#include <filesystem>
#include <iostream>
#include "preprocess.h"

namespace fs = std::filesystem;

void processChessPieces(const std::string& rootDir) {
    try {
        ChessDatabase db("test.db");

        // 定义支持的图片扩展名（可根据需要扩展）
        std::vector<std::string> supportedExtensions = {".png", ".bmp", ".jpg", ".jpeg"};

        // 遍历根目录下的所有子文件夹
        for (const auto& entry : fs::directory_iterator(rootDir)) {
            if (entry.is_directory()) {
                std::string pieceType = entry.path().filename().string();
                std::cout << "Processing piece type: " << pieceType << std::endl;

                // 遍历子文件夹中的所有文件
                int fileIndex = 1;
                for (const auto& file : fs::directory_iterator(entry.path())) {
                    // 检查文件扩展名是否在支持列表中
                    std::string ext = file.path().extension().string();
                    std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); // 统一转为小写

                    if (std::find(supportedExtensions.begin(), supportedExtensions.end(), ext) != supportedExtensions.end()) {
                        std::string imagePath = file.path().string();
                        std::cout << "Processing file: " << imagePath << std::endl;
						cv::Mat croppedImage;
                        try {
							try{
							ImageProcessor processor(imagePath);
								if (processor.processImage()) {
									//cv::imshow("原始图像", processor.getResultImage());
									//cv::imshow("裁剪结果", processor.getCroppedImage());
									croppedImage=processor.getCroppedImage();
									//cv::waitKey(0);
								}
							} catch (const std::exception& e) {
								std::cerr << "错误: " << e.what() << std::endl;
								//return -1;
							}
                            // 提取特征（自动获取颜色）
                            ChessDatabase::ChessPiece piece = extractChessPieceFeatures(
                                croppedImage,
                                1.0,
                                0.0, // y坐标保持为0（可根据需要调整）
                                pieceType
                            );

                            // 存储到数据库
                            db.addChessPiece(piece);
                            std::cout << "Stored piece: " << pieceType << " " << fileIndex 
                                      << " successfully!" << std::endl;
                        } catch (const std::exception& e) {
                            std::cerr << "Error processing " << imagePath 
                                      << ": " << e.what() << std::endl;
                        }

                        fileIndex++;
                    }
                }
            }
        }

        // 打印数据库内容（可选）
        // db.printAllChessPieces();
    } catch (const std::exception& e) {
        std::cerr << "Fatal error: " << e.what() << std::endl;
    }
}

void testChessRecognition(const std::string& imagePath) {
    try {
        // 初始化数据库（假设数据库已存在且有数据）
        ChessDatabase db("test.db");
		cv::Mat croppedImage;
		try{
			ImageProcessor processor(imagePath);
			if (processor.processImage()) {
			//cv::imshow("原始图像", processor.getResultImage());
			cv::imshow("裁剪结果", processor.getCroppedImage());
			croppedImage=processor.getCroppedImage();
			cv::waitKey(0);
			}
			} catch (const std::exception& e) {
				std::cerr << "错误: " << e.what() << std::endl;
				//return -1;
				}
        
        // 提取测试图像特征（这里可以传入实际坐标，示例用固定值）
        ChessDatabase::ChessPiece testPiece = extractChessPieceFeatures(
            croppedImage,
            1.0,  // x坐标示例值
            0.0,  // y坐标示例值
            "unknown" // 初始类型设为unknown
        );
        
        // 执行匹配
        std::string matchedType = db.matchChessPiece(testPiece);
        
        // 输出结果
        std::cout << "\n=== 识别结果 ===" << std::endl;
        std::cout << "图像路径: " << imagePath << std::endl;
        std::cout << "识别类型: " << matchedType << std::endl;
        std::cout << "颜色: " << testPiece.color << std::endl;
        std::cout << "Hu矩特征: ";
        for (double hu : testPiece.huMoments) {
            std::cout << hu << " ";
        }
        std::cout << "\n================================\n" << std::endl;
        
    } catch (const std::exception& e) {
        std::cerr << "识别测试失败: " << e.what() << std::endl;
    }
}